package com.app.service.Impl;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.app.common.SystemConstant;
import com.app.mapper.AreaMapper;
import com.app.mapper.UserIntegralMapper;
import com.app.mapper.UserMapper;
import com.app.model.AreaModel;
import com.app.model.UserIntegralModel;
import com.app.model.UserModel;
import com.app.service.AreaService;
import com.app.service.UserService;
import com.app.util.*;
import com.app.vo.UserVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.security.auth.login.LoginException;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {


    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserIntegralMapper userIntegralMapper;
    @Autowired
    private AreaService areaService;
    @Autowired
    private AreaMapper areaMapper;

    @Override
    public UserModel wxLogin(String code, String mobileCode, HttpServletRequest request) throws LoginException {
        //获取手机号
        String mobile = WechatUtil.getMobile(mobileCode);
            //获取openid
            String openid = WechatUtil.getOpenid(code);

        if (openid == null) {
            throw new LoginException("openid为空");
        }
        //根据openid查询用户信息
        UserModel user = userMapper.getByOpenid(openid);
        if (user == null) {
            //当前是新用户，自动注册
            user = new UserModel();
            user.setOpenId(openid);
            user.setPhoneNumber(mobile);
            user.setName("用户" + GetUUID.getUUID(8));
            user.setAvatar(SystemConstant.DEFAULT_FACE_URL);//首次登录设置默认头像
            user.setCreateTime(CommonHelp.getNowTimestamp());
            user.setUpdateTime(CommonHelp.getNowTimestamp());
            user.setVillageId(0);
            user.setStatus(1);
            user.setIntegral(0);
            String ip = IpUtil.getIpAddress(request);
            user.setLastLoginIp(ip);
            user.setLastLoginTime(CommonHelp.getNowTimestamp());
            userMapper.insert(user);
            return userMapper.getByOpenid(openid);
        }
        user.setPhoneNumber(mobile);
        userMapper.updateById(user);
        UserModel tbUser = new UserModel();
        tbUser.setName(user.getName());
        tbUser.setOpenId(user.getOpenId());
        tbUser.setPhoneNumber(mobile);
        tbUser.setId(user.getId());
        tbUser.setAvatar(user.getAvatar());
        String ip = IpUtil.getIpAddress(request);
        tbUser.setLastLoginIp(ip);
        tbUser.setLastLoginTime(CommonHelp.getNowTimestamp());
        return tbUser;
    }

    @Override
    public UserModel getUserByMobile(String mobile1) {
        Map<String, Object> map = new HashMap<>();
//        map.put("name", mobile1);
        map.put("phone_number", mobile1);
        List<UserModel> userList = userMapper.selectByMap(map);
        if (userList.isEmpty()) {
            return null;
        } else {
            return userList.get(0);
        }
    }

    @Override
    public void updateUserInfo(UserModel user) {
        userMapper.updateById(user);
    }

    @Override
    public UserModel updateAvatar(UserModel model) {
        userMapper.updateById(model);
        return userMapper.selectById(model.getId());
    }

    @Override
    public UserVo selectUserList(Integer page, Integer limit, String name, Integer villageId,Integer auditStatus) {
        UserModel model = new UserModel();
        model.setPage((page - 1) * limit);
        model.setLimit(limit);
        model.setAuditStatus(auditStatus);
        model.setVillageId(villageId);
        model.setKeyword(name);
        List<UserModel> userModels = userMapper.selectUserList(model);
        if (!userModels.isEmpty()) {
            for (int i = 0; i < userModels.size(); i++) {
                if (userModels.get(i).getVillageId() != 0) {
                    AreaModel villageAreaModel = areaService.selectById(userModels.get(i).getVillageId());
                    AreaModel townAreaModel = areaService.selectById(villageAreaModel.getPid());
                    AreaModel cityAreaModel = areaService.selectById(townAreaModel.getPid());
                    userModels.get(i).setVillageText(cityAreaModel.getName() + "/" + townAreaModel.getName() + "/" + villageAreaModel.getName());
                } else {
                    userModels.get(i).setVillageText("");
                }
            }
            for (UserModel userModel : userModels) {
                if (userModel.getAuditStatus() != null && userModel.getAuditStatus() == 1) {
                    userModel.setAuditStatusText("未实名");
                }
                if (userModel.getAuditStatus() != null && userModel.getAuditStatus() == 2) {
                    userModel.setAuditStatusText("已实名");
                }
                if (userModel.getAuditStatus() != null && userModel.getAuditStatus() == 3) {
                    userModel.setAuditStatusText("审核中");
                }
                if (userModel.getAuditStatus() != null && userModel.getAuditStatus() == 4) {
                    userModel.setAuditStatusText("未通过");
                }
                if (userModel.getSex() == 1) {
                    userModel.setSexText("男");
                }
                if (userModel.getSex() == 2) {
                    userModel.setSexText("女");
                }
            }
        }
        int count = userMapper.getCount(model);
        UserVo vo = new UserVo();
        vo.setList(userModels);
        vo.setCount(count);
        return vo;
    }

    @Override
    public List<UserIntegralModel> selectIntegral(Integer id) {
        UserModel userModel = userMapper.selectById(id);
        QueryWrapper<UserIntegralModel> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", id);
        List<UserIntegralModel> userIntegralModel = userIntegralMapper.selectList(queryWrapper);
        for (int i = 0; i < userIntegralModel.size(); i++) {
            if (userIntegralModel.get(i).getType() == 1) {
                userIntegralModel.get(i).setTypeText("报名活动");
            }
            if (userIntegralModel.get(i).getType() == 3) {
                userIntegralModel.get(i).setTypeText("兑换商品");
            }
        }
        return userIntegralModel;
    }

    // userIntegralModel.get(i).setAvatar(userModel.getAvatar());
//            userIntegralModel.get(i).setPhoneNumber(userModel.getPhoneNumber());
//            userIntegralModel.get(i).setIdCard(userModel.getIdCard());
//            userIntegralModel.get(i).setIntegralAmount(userModel.getIntegral());
    @Override
    public UserModel selectUserById(Integer id) {
        UserModel model = userMapper.selectById(id);
        AreaModel townId = areaMapper.selectById(model.getVillageId());//村
        QueryWrapper<AreaModel> queryWrapper = new QueryWrapper<>();
        if (townId != null && townId.getPid() != null) {
            model.setTownId(townId.getPid());
            queryWrapper.eq("id", townId.getPid());
        }
        List<AreaModel> areaModels = areaMapper.selectList(queryWrapper);//镇
        if (!areaModels.isEmpty() && areaModels.get(0).getPid() != null) {
            model.setCityId(areaModels.get(0).getPid());
        }
        return model;
    }

    @Override
    public UserModel getUserByOpenid(String mobile) {
        QueryWrapper<UserModel> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("open_id", mobile);
        return userMapper.selectOne(queryWrapper);
    }

    @Override
    public void updateAuditStatus(Integer id, Integer auditStatus,String remark) {
        UserModel model = new UserModel();
        model.setAuditStatus(auditStatus);
        model.setRemark(remark);
        model.setId(id);
        userMapper.updateById(model);
    }
}
